from fastapi import APIRouter, HTTPException, Query
from typing import List, Dict, Any, Optional
from datetime import datetime
from pydantic import BaseModel
import logging

from utils.statistics_curd import get_multidimensional_workhours_statistics, get_employee_workhours_statistics

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建路由
router = APIRouter(
    tags=["statistics"]
)

# 统计响应模型
class StatisticResponse(BaseModel):
    labels: List[str]
    datasets: List[Dict[str, Any]]
    summary: Optional[Dict[str, Any]] = None

# 多维度工时统计响应模型
class MultidimensionalWorkhoursResponse(BaseModel):
    data: List[Dict[str, Any]]
    dimensions: List[str]
    summary: Dict[str, Any]

# 员工工时统计请求模型
class EmployeeWorkhoursRequest(BaseModel):
    employee_ids: List[str]
    start_date: str
    end_date: str

# 员工工时统计响应模型
class EmployeeWorkhoursResponse(BaseModel):
    data: List[Dict[str, Any]]
    summary: Dict[str, Any]

# 默认日期处理函数
def get_default_dates():
    today = datetime.today()
    # 默认为过去3个月到今天，而不是当月1号到今天
    three_months_ago = today.replace(month=today.month-3 if today.month > 3 else today.month+9, 
                                    year=today.year if today.month > 3 else today.year-1)
    start_date = three_months_ago.strftime("%Y-%m-%d")
    today_str = today.strftime("%Y-%m-%d")
    return start_date, today_str

@router.get("/multidimensional-workhours", response_model=MultidimensionalWorkhoursResponse)
async def get_multidimensional_workhours(
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    dimensions: str = Query("dept1", description="统计维度，多个维度用逗号分隔，可选值：affiliation,dept1,dept2,dept3")
):
    """
    获取多维度工时统计数据
    
    - **start_date**: 开始日期，格式：YYYY-MM-DD
    - **end_date**: 结束日期，格式：YYYY-MM-DD
    - **dimensions**: 统计维度，多个维度用逗号分隔，可选值：affiliation,dept1,dept2,dept3
    """
    try:
        # 如果未提供日期，设置默认值
        if not start_date or not end_date:
            start_date, end_date = get_default_dates()
            
        logger.info(f"获取多维度工时统计数据: 开始日期={start_date}, 结束日期={end_date}, 维度={dimensions}")
        
        # 解析维度参数
        dimension_list = dimensions.split(",")
        
        # 获取统计数据
        stats = get_multidimensional_workhours_statistics(start_date, end_date, dimension_list)
        
        # 计算汇总数据
        total_day_hours = sum(item['day_total_hours'] for item in stats)
        total_night_hours = sum(item['night_hours'] for item in stats)
        total_overtime_hours = sum(item['overtime_hours'] for item in stats)
        total_records = sum(item['record_count'] for item in stats)
        
        summary = {
            "total_day_hours": round(total_day_hours, 2),
            "total_night_hours": round(total_night_hours, 2),
            "total_overtime_hours": round(total_overtime_hours, 2),
            "total_records": total_records,
            "period": f"{start_date} 至 {end_date}"
        }
        
        return {
            "data": stats,
            "dimensions": dimension_list,
            "summary": summary
        }
    except ValueError as e:
        logger.error(f"参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"获取多维度工时统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取多维度工时统计数据失败: {str(e)}")

@router.post("/employee-workhours", response_model=EmployeeWorkhoursResponse)
async def get_employee_workhours(request: EmployeeWorkhoursRequest):
    """
    获取特定员工在指定日期范围内的工时统计数据
    
    - **employee_ids**: 员工ID列表
    - **start_date**: 开始日期，格式：YYYY-MM-DD
    - **end_date**: 结束日期，格式：YYYY-MM-DD
    """
    try:
        logger.info(f"获取员工工时统计数据: 员工IDs={request.employee_ids}, 开始日期={request.start_date}, 结束日期={request.end_date}")
        
        # 获取员工工时统计数据
        stats = get_employee_workhours_statistics(request.employee_ids, request.start_date, request.end_date)
        
        # 计算汇总数据
        total_work_days = sum(item.get('total_work_days', 0) for item in stats)
        total_day_work_hours = sum(item.get('day_total_work_hours', 0) for item in stats)
        total_night_work_hours = sum(item.get('night_work_hours', 0) for item in stats)
        total_overtime_hours = sum(item.get('overtime_hours', 0) for item in stats)
        
        # 汇总不同类型的加班工时
        overtime_by_type = {}
        for employee in stats:
            if 'overtime_details' in employee:
                for ot_type, hours in employee['overtime_details'].items():
                    if ot_type in overtime_by_type:
                        overtime_by_type[ot_type] += hours
                    else:
                        overtime_by_type[ot_type] = hours
        
        summary = {
            "total_employees": len(stats),
            "total_work_days": total_work_days,
            "total_day_work_hours": round(total_day_work_hours, 2),
            "total_night_work_hours": round(total_night_work_hours, 2),
            "total_overtime_hours": round(total_overtime_hours, 2),
            "overtime_by_type": {k: round(v, 2) for k, v in overtime_by_type.items()},
            "period": f"{request.start_date} 至 {request.end_date}"
        }
        
        return {
            "data": stats,
            "summary": summary
        }
    except ValueError as e:
        logger.error(f"参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"获取员工工时统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取员工工时统计数据失败: {str(e)}") 